<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center space-x-4">
            <ULink to="/" class="flex items-center space-x-2">
              <UIcon name="i-heroicons-camera" class="h-8 w-8 text-primary-600" />
              <h1 class="text-2xl font-bold text-gray-900">维扣图元</h1>
            </ULink>
            <!-- 桌面端导航菜单 -->
            <div class="hidden md:flex space-x-4">
              <ULink to="/content" class="flex items-center space-x-1 px-3 py-2 text-gray-600 hover:text-primary-600">
                <UIcon name="i-heroicons-document-text" class="h-5 w-5" />
                <span>内容</span>
              </ULink>
              <ULink to="/explore" class="flex items-center space-x-1 px-3 py-2 text-gray-600 hover:text-primary-600">
                <UIcon name="i-heroicons-globe-alt" class="h-5 w-5" />
                <span>发现</span>
              </ULink>
              <ULink to="/feedback/list" class="flex items-center space-x-1 px-3 py-2 text-gray-600 hover:text-primary-600">
                <UIcon name="i-heroicons-chat-bubble-left-right" class="h-5 w-5" />
                <span>建议反馈</span>
              </ULink>
            </div>
            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden ml-auto mr-4 flex items-center justify-center">
              <UIcon :name="mobileMenuOpen ? 'i-heroicons-x-mark' : 'i-heroicons-bars-3'" class="h-6 w-6 text-gray-600" />
            </button>
          </div>
          <div class="flex items-center space-x-4">
            <template v-if="loading">
              <div class="w-24 h-8 bg-gray-100 animate-pulse rounded-md"></div>
            </template>
            <template v-else-if="!isLoggedIn">
              <ULink to="/user/login" class="text-gray-600 hover:text-gray-900">
                <UButton color="primary" variant="ghost" class="flex items-center space-x-1">
                  <UIcon name="i-heroicons-arrow-right-on-rectangle" class="h-5 w-5" />
                  <span>登录</span>
                </UButton>
              </ULink>
              <ULink to="/user/register">
                <UButton color="primary" class="flex items-center space-x-1">
                  <UIcon name="i-heroicons-user-plus" class="h-5 w-5" />
                  <span>注册</span>
                </UButton>
              </ULink>
            </template>
            <template v-else>
              <UDropdown :items="userMenuItems" :ui="{ item: { base: 'flex items-center gap-2 cursor-pointer' } }">
                <div class="flex items-center space-x-2 cursor-pointer hover:text-primary-600 transition-colors duration-200">
                  <UAvatar
                    size="sm"
                    :src="userAvatar"
                    :ui="{ background: 'bg-primary-100' }"
                  />
                  <span class="text-gray-600">{{ userName }}</span>
                  <UIcon name="i-heroicons-chevron-down" class="h-4 w-4" />
                </div>
              </UDropdown>
            </template>
          </div>
        </div>
      </div>
    </nav>

    <!-- 移动端导航菜单 -->
    <div v-if="mobileMenuOpen" class="mobile-menu md:hidden">
      <ULink to="/content" class="nav-item flex items-center space-x-2">
        <UIcon name="i-heroicons-document-text" class="h-5 w-5 text-primary-600" />
        <span>内容</span>
      </ULink>
      <ULink to="/explore" class="nav-item flex items-center space-x-2">
        <UIcon name="i-heroicons-globe-alt" class="h-5 w-5 text-primary-600" />
        <span>发现</span>
      </ULink>
      <ULink to="/feedback/list" class="nav-item flex items-center space-x-2">
        <UIcon name="i-heroicons-chat-bubble-left-right" class="h-5 w-5 text-primary-600" />
        <span>建议反馈</span>
      </ULink>
    </div>

    <!-- 页面内容 -->
    <slot />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { auth } from '../utils/auth'

const isLoggedIn = ref(false)
const userId = ref('')
const userName = ref('')
const userAvatar = ref('')
const loading = ref(true)
const mobileMenuOpen = ref(false)

// 切换移动端菜单
const toggleMobileMenu = () => {
  mobileMenuOpen.value = !mobileMenuOpen.value
}

// 路由守卫
const route = useRoute()
const router = useRouter()

// 监听登录状态变化
const updateUserInfo = async () => {
  const storedUserId = localStorage.getItem('user_id')
  const storedUserName = localStorage.getItem('username')
  
  if (storedUserId) {
    isLoggedIn.value = true
    userId.value = storedUserId
    
    // 获取用户信息，包括头像和昵称
    const userInfo = await auth.getCurrentUser()
    if (userInfo) {
      // 优先使用昵称，如果没有则使用用户名
      userName.value = userInfo.nickname || storedUserName
      
      if (userInfo.avatar) {
        userAvatar.value = userInfo.avatar
      } else {
        // 设置默认头像
        userAvatar.value = 'https://avatars.githubusercontent.com/u/739984?v=4'
      }
    } else {
      userName.value = storedUserName
    }
  } else {
    isLoggedIn.value = false
    userId.value = ''
    userName.value = ''
    userAvatar.value = ''
  }
  loading.value = false
}

// 在组件挂载时检查用户登录状态
onMounted(async () => {
  if (process.client) {
    await updateUserInfo()
  }
})

// 监听localStorage变化
if (process.client) {
  // 监听storage事件（跨页面）
  window.addEventListener('storage', async (event) => {
    if (event.key === 'user_id' || event.key === 'username') {
      await updateUserInfo()
    }
  })
  
  // 监听自定义登录状态变化事件（同页面内）
  window.addEventListener('login-state-changed', async () => {
    await updateUserInfo()
  })
  
  // 监听用户信息变化事件（如头像更新）
  window.addEventListener('user-info-changed', async () => {
    await updateUserInfo()
  })

  // 监听路由变化
  watchEffect(() => {
    // 检查用户登录状态并处理路由
    const storedUserId = localStorage.getItem('user_id')
    if (storedUserId && route.path === '/') {
      router.push('/content')
    }
  })
}

// 用户菜单项
const userMenuItems = [
  [
    {
      label: '个人主页',
      icon: 'i-heroicons-user',
      click: () => navigateTo('/user/me')
    },
    {
      label: '我的收藏',
      icon: 'i-heroicons-heart',
      click: () => navigateTo('/user/favorites')
    },
    {
      label: '我的反馈',
      icon: 'i-heroicons-clipboard-document-list',
      click: () => navigateTo('/feedback/my-feedback')
    },
    {
      label: '设置',
      icon: 'i-heroicons-cog-6-tooth',
      click: () => navigateTo('/user/settings')
    },
  ],
  [
    {
      label: '退出登录',
      icon: 'i-heroicons-arrow-right-on-rectangle',
      click: () => handleLogout()
    }
  ]
]

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('user_id')
  localStorage.removeItem('username')
  auth.logout() // 调用auth的logout方法清除token
  isLoggedIn.value = false
  userId.value = ''
  navigateTo('/')
}
</script>